/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proxy;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

/**
 *
 * @author Hue
 */
public class InitServlet extends HttpServlet {
    public static final String PROXY_VPN = "PROXY_VPN";
    
    @Override
    public void init() throws ServletException {
        new Restart().start();
        
        ServletConfig config = getServletConfig();
        String configFile = getServletContext().getRealPath("config.properties");
        OpenURL.CONFIG_FILE = configFile;
        Properties cf = loadConfigFile(configFile);
        getServletContext().setAttribute("configFile", cf);

        if("true".equals(config.getInitParameter("isProxyServer"))) {
            OpenURL.WAIT = getWait(config);
            String clientsFile = getServletContext().getRealPath("clients.properties");
            String serversFile = getServletContext().getRealPath("servers.txt");
            try {
                VPN vpn = new VPN(cf, clientsFile, serversFile);
                new Thread(vpn).start();
                getServletContext().setAttribute(PROXY_VPN, vpn);
            }
            catch(IOException ex) {
                System.out.println("InitServlet.init(): " + ex);
            }
        }
    }
    
    private Properties loadConfigFile(String filename) {
        Properties config = new Properties();
        try {
            FileInputStream in = new FileInputStream(filename);
            config.load(in);
            in.close();
        }
        catch(IOException ex) {
            System.out.println(ex);
        }
        return config;
    }
    
    private int getWait(ServletConfig config) {
        try {
            return Integer.parseInt(config.getInitParameter("wait"));
        }
        catch(Exception ex) {
            //ignore
        }
        return 90;
    }
}
